package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.service.SpecParamService;
import com.leyou.item.service.SpuDetailService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @ClassName : SpuDetailServiceImpl  //类名
 * @Description :   //描述
 * @Author : qingfeng  //作者
 * @Date: 2020-09-18 10:56  //时间
 */
@Service
public class SpuDetailServiceImpl extends ServiceImpl<SpuDetailMapper, SpuDetail> implements SpuDetailService {

    private final SpuMapper spuMapper;
    private final SpecParamService paramService;

    public SpuDetailServiceImpl(SpuMapper spuMapper, SpecParamService paramService) {
        this.spuMapper = spuMapper;
        this.paramService = paramService;
    }


    @Override
    public List<SpecParamDTO> querySpecValues(Long id, Boolean searching) {
        /**
         * @Description //TODO 查询商品规格参数键值对
         * @Param [id, searching]
         * @return java.util.List<com.leyou.item.dto.SpecParamDTO>
         */
        //1 准备规格参数value
        //1.1 根据id查询spuDetail
        SpuDetail detail = getById(id);
        //1.2 获取其中的规格参数键值对,转为一个map
        Map<Long, Object> specValues = JsonUtils.toMap(detail.getSpecification(), Long.class, Object.class);
        //2 准备规格参数对象
        //2.1 根据id查询spu，获取商品分类信息
        Spu spu = spuMapper.selectById(id);
        //2.2 根据分类id查询规格参数集合，如果searching不为空，还要加上searching条件
        List<SpecParamDTO> params = paramService.querySpecParams(spu.getCid3(), null, searching);
        //3 找到param的value，并存储
        for (SpecParamDTO param : params) {
            param.setValue(specValues.get(param.getId()));
        }
        return params;
    }
}
